const http = require('../../utils/http.js');
const baseUrl = 'http://localhost:5000'; // record.py ip地址

Page({
  data: {
    base_candidate_info: {
      id: '',
      id_number: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      political_status_id: '',
      foreign_language_id: '',
      phone: '',
      password: '',
      recognitionResult: '',
      recording: false,  // 用于标记当前是否正在录音
    isPaused: false,   // 用于标记录音是否处于暂停状态
    recordFilePath: '',  // 用于保存录音文件的临时路径
    editableContent: '', // 用于保存识别后文本内容的初始化
    buttonText: '开始录音', // 新增按钮文本控制变量
    },
    genderOptions: ['男', '女'],
    genderIndex: null,
    ethnicityOptions: [],
    ethnicityIndex: null,
    politicalStatusOptions: [],
    politicalStatusIndex: null,
    foreignLanguageOptions: [],
    foreignLanguageIndex: null,
    recordedText:null
  },
  // 日期格式化函数
  formatDate(dateString) {
    if (!dateString) return '';

    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
  },

  onLoad() {
    // 获取所有选项数据
    const ethnicityPromise = this.fetchOptions('/ethnicity/list', 'ethnicityOptions');
    const politicalStatusPromise = this.fetchOptions('/politicalstatus/list', 'politicalStatusOptions');
    const foreignLanguagePromise = this.fetchOptions('/foreignlanguage/list', 'foreignLanguageOptions');
  
    // 等待所有请求完成
    Promise.all([ethnicityPromise, politicalStatusPromise, foreignLanguagePromise]).then(() => {
      // console.log(this.data.ethnicityOptions)
      // 确保选项数据已加载后，设置默认值
      const storedInfo = wx.getStorageSync('base_candidate_info');
      if (storedInfo) {
        //   storedInfo.birth_date = this.formatDate(storedInfo.birth_date)
        this.setData({
          base_candidate_info: storedInfo,
          genderIndex: this.data.genderOptions.indexOf(storedInfo.gender),
          ethnicityIndex: this.findIndexById(this.data.ethnicityOptions, storedInfo.ethnicity_id),
          politicalStatusIndex: this.findIndexById(this.data.politicalStatusOptions, storedInfo.political_status_id),
          foreignLanguageIndex: this.findIndexById(this.data.foreignLanguageOptions, storedInfo.foreign_language_id),
        });
      } else {
        wx.showToast({ title: '请先注册考生信息', icon: 'none' });
      }
    }).catch(err => {
      console.error('加载选项数据失败:', err);
    });
  },  

  findIndexById(options, id) {
    return options.findIndex(option => option.id == id);
  },

  fetchOptions(endpoint, stateKey) {
    return new Promise((resolve, reject) => {
      http.get(endpoint).then(res => {
        if (res.data && res.data.code === 200) {
          this.setData({ [stateKey]: res.data.data }, resolve); // 数据设置完成后调用 resolve
        } else {
          reject('数据加载失败');
        }
      }).catch(err => {
        console.error(`加载 ${stateKey} 数据失败:`, err);
        reject(err);
      });
    });
  },
  handleDateChange(e) {
    this.setData({
      birth_date: e.detail.value // 直接绑定选中的日期
    });
  },
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`${field}Index`]: e.detail.value
    });
  },

  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [field]: e.detail.value
    });
  },

  handleSubmit(){
    const base_candidate_info = {
      id_number: this.data.base_candidate_info.id_number,
      name: this.data.base_candidate_info.name,
      gender: this.data.genderOptions[this.data.genderIndex] || '', 
      birth_date: this.data.base_candidate_info.birth_date,
      ethnicity_id: this.data.ethnicityOptions[this.data.ethnicityIndex].id, 
      political_status_id: this.data.politicalStatusOptions[this.data.politicalStatusIndex].id, 
      foreign_language_id: this.data.foreignLanguageOptions[this.data.foreignLanguageIndex].id, 
      phone: this.data.base_candidate_info.phone,
    };
    console.log(base_candidate_info)
    http.post("/candidate/updateBasicInfo",base_candidate_info).then(res=>{
      console.log(res);
      if(res.data.code == 200){
        wx.setStorageSync('base_candidate_info', base_candidate_info)
        wx.showToast({
          title: '基本信息更新成功',
          duration:2000
        })
        // 跳转页面
        wx.navigateTo({
          url: '/pages/edit-baoming/edit-baoming',
        })
      }
    }).catch(err=>{
      console.log(err);
      wx.showToast({
        title: '基本信息更新失败',
        duration:2000
      })
    })
  },


  onSubmit() {
    const { id_number, name, genderIndex, birth_date, phone, password } = this.data;
    const errors = [];

    if (!id_number) errors.push('身份证号不能为空');
    // else if (id_number.length !== 18) errors.push('身份证号必须为18位');

    if (!name) errors.push('姓名不能为空');

    if (genderIndex === null) errors.push('请选择性别');

    if (!birth_date) errors.push('请选择出生日期');

    if (!phone) errors.push('手机号不能为空');

    if (!password) errors.push('密码不能为空');
    else if (password.length < 6) errors.push('密码长度必须大于6位');

    if (errors.length > 0) {
      wx.showToast({ title: errors[0], icon: 'none' });
      return;
    }
  },

  checkRecordPermission() {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.record']) {
                    console.log('已获取录音权限，直接resolve');
                    resolve();
                } else {
                    wx.authorize({
                        scope: 'scope.record',
                        success() {
                            console.log('申请录音权限成功，resolve');
                            resolve();
                        },
                        fail() {
                            console.log('申请录音权限失败，reject');
                            reject('用户未授予录音权限');
                        }
                    });
                }
            },
            fail() {
                console.log('获取录音权限设置失败，reject');
                reject('获取录音权限设置失败');
            }
        });
    });
},
  


toggleRecording() {
    const that = this;
    if (that.data.recording) {
        // 停止录音逻辑
        that.setData({ recording: false });
        const recorderManager = wx.getRecorderManager();
        recorderManager.stop();
        recorderManager.onStop((res) => {
            // 将录音文件临时路径存储到本地存储
            wx.setStorageSync('recordPath', res.tempFilePath);
            that.setData({ recordFilePath: res.tempFilePath });
            // 这里调用后端代码进行录音转文字
            // that.setData({ editableContent: '转换后的文本内容' });
            that.setData({ buttonText: '开始录音' });
        });
    } else {
        that.checkRecordPermission().then(() => {
            // 开始录音逻辑
            that.setData({ recording: true });
            const recorderManager = wx.getRecorderManager();
            recorderManager.start({
                format: 'wav', // 设置为wav格式
                duration: 60000, 
                sampleRate: 44100, 
                numberOfChannels: 1, 
                encodeBitRate: 96000
            });
            that.setData({ buttonText: '停止录音' });
        }).catch((error) => {
            wx.showToast({
                title: 'error',
                icon:'none'
            });
        });
    }
},

// 上传录音并进行语音识别函数
uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
        wx.showToast({ title: '请先录制录音', icon: 'none' });
        return;
    }
    wx.uploadFile({
        filePath: this.data.recordFilePath,
        name: 'audio_data',
        url: baseUrl + '/recognize',
        formData: {},
        header: { 'content-type': 'multipart/form-data' },
        success: function (res) {
            try {
                const responseData = JSON.parse(res.data);
                if (responseData.code === 200 && responseData.text) {
                    this.setData({
                        editableContent: responseData.text
                    });
                    this.setData({
                        base_candidate_info:{
                            'id_number': 123456,
                        'name': '张三',
                        'gender': '男',
                        'birth_date': "2001-12-11",
                        'ethnicity_id': 1,
                        'political_status_id': 3,
                        'foreign_language_id': 1,
                        'phone': 12345,
                        'password': 123456,
                        },
                        genderIndex: 0,
                        ethnicityIndex: 0,
                        politicalStatusIndex: 2,
                        foreignLanguageIndex: 0
                        });
                    wx.request({
                        url: 'http://localhost:8080/files/files/fillData',
                        method: 'POST',
                        header: {
                            'content-type': 'application/json' // 设置请求头为JSON格式
                        },
                        data: {"txt":responseData.text},
                        success:function(res){
                            console.log(res);
                        },
                        fail:function(res){
                            console.log(res);
                        }
                    })
                } else {
                    wx.showToast({
                        title: responseData.message || '识别出现其他错误',
                        icon: 'none',
                        duration: 2000
                    });
                }
            } catch (e) {
                console.log('无法解析识别结果：', e);
                console.log('接收到的原始返回数据：', res.data);
            }
        }.bind(this),
        fail: function (err) {
            console.log('上传失败，详细错误信息：', err);
            if (err.errMsg.includes('network')) {
                wx.showToast({
                    title: '网络连接出现问题，请检查网络设置后重试',
                    icon: 'none',
                    duration: 2000
                });
            } else if (err.errMsg.includes('file')) {
                wx.showToast({
                    title: '文件相关错误，请检查音频文件是否正常',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                wx.showToast({
                    title: '上传出现其他未知错误，请稍后重试',
                    icon: 'none',
                    duration: 2000
                });
            }
        }
    });
},
// 发送识别结果到另一个端口的函数，确保以JSON格式发送
sendRecognitionResultToServer(result) {
    const resultToSend = {
        text: result
    };
    return new Promise((resolve, reject) => {
        const options = {
            url: 'http://localhost:8080/files/files/fillData',
            method: 'POST',
            header: {
                'content-type': 'application/json' // 设置请求头为JSON格式
            },
            data: {}
        };
        try {
            options.data = JSON.stringify(resultToSend); // 对要发送的数据进行JSON序列化
        } catch (jsonError) {
            console.log('JSON序列化识别结果失败:', jsonError);
            reject('识别结果数据格式错误');
            return;
        }
        http.request(options).then(res => {
            if (res.data && res.data.code === 200) {
                console.log('识别结果已成功发送到服务器');
                resolve();
            } else {
                console.log('发送识别结果到服务器失败', res);
                reject('发送识别结果到服务器失败');
            }
        }).catch(err => {
            console.log('发送识别结果到服务器请求失败', err);
            reject(err);
        });
    });
}
});